package tag39_03_09.threadsWeiter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

class Logger{
	
	StringBuilder sb = new StringBuilder();
	
	
	// Speicher jede Nachricht in der Form: SS:MM:ss:mm - caller - msg
 	public synchronized void addMsg(String caller, String masg){
 		
 		Calendar cal = Calendar.getInstance();
		String zeit = String.format("%02d:%02d:%02d:%03d", 
				cal.get(Calendar.HOUR_OF_DAY),
				cal.get(Calendar.MINUTE),
				cal.get(Calendar.SECOND),
				cal.get(Calendar.MILLISECOND)); //SS:MM:ss:mm
		
		sb.append(zeit);
		sb.append(" - ");
		sb.append(caller);
		sb.append(" - ");
		sb.append(masg);
		sb.append("\n");
	}
	
 	
 	synchronized String getText(){
 		return sb.toString();	
 	}
}


// 1. Zeit formatieren
// 2. In der main am Ende den Logger-Text ausgeben. 
//    Sicher stellen, das der Thread th davor beendet wurde

public class Th19_LoggerThreadsicher {
	
	static Logger mainLogger = new Logger();
	

	public synchronized static void main(String[] args) throws InterruptedException {

		Thread th = new Thread() {
			public void run() {
				for (int i = 0; i < 200; i++) {
					mainLogger.addMsg("th", "Hallo from th");
				}
				
			}
		};
		th.start();
		
		for (int i = 0; i < 200; i++) {
			mainLogger.addMsg("main", "Hallo from main");
		}
		
		th.join();
		System.out.println(mainLogger.getText());
		
		
		Date fecha = new Date();
		System.out.println(fecha.toString());
		
		DateFormat hora = new SimpleDateFormat("HH:mm:ss");
		String parse = hora.format(fecha);
		System.out.println(parse);
	}

}
